<template>
  <a-layout style="height: 100vh;">
    <!-- 侧边栏部分 -->
    <a-layout-sider v-model:collapsed="collapsed" :trigger="null" collapsible class="aside">
      <h2 style="text-align: center ;font-size: 24px; color: #fff; margin: 10px;">后台管理系统</h2>
      <div class="logo">
      </div>
      <a-menu v-model:openKeys="openKeys" v-model:selectedKeys="selectedKeys" style="width: 100%" mode="inline"
        :items="items" @click="handleClick" theme="dark"></a-menu>
    </a-layout-sider>
    <a-layout>
      <!-- 头部 -->
      <a-layout-header style="background: #fff; padding: 5px 10px">
        <Header @toggleCollapsed="toggleCollapsed"></Header>
      </a-layout-header>
      
      <!-- 面包屑 -->
      <div style="float:left;background: #fff; padding: 0 24px; border-bottom: 1px solid #f0f0f0;">
        <Breadcrumb />
      </div>
      <!-- 主体body -->
      <a-layout-content
        :style="{ margin: '10px 16px', padding: '10px 24px', background: '#fff', minHeight: '280px', overflow: 'auto' }">
        <!-- 内容区域 -->
        <router-view></router-view>
      </a-layout-content>
      <a-layout-footer style="text-align: center;">
        @copyright 2025-present by XE
      </a-layout-footer>
    </a-layout>

  </a-layout>
</template>
<script setup>
import {
  UserOutlined, MailOutlined, AppstoreOutlined, SettingOutlined, UploadOutlined, 
  MenuUnfoldOutlined, MenuFoldOutlined, UsergroupDeleteOutlined, BarChartOutlined,
  UnorderedListOutlined, EditOutlined, DashboardOutlined, HomeOutlined,
  FileTextOutlined, PlusOutlined, MessageOutlined, ProfileOutlined
} from '@ant-design/icons-vue';

// 图标映射对象
const iconMap = {
  'UserOutlined': UserOutlined,
  'MailOutlined': MailOutlined,
  'AppstoreOutlined': AppstoreOutlined,
  'SettingOutlined': SettingOutlined,
  'UploadOutlined': UploadOutlined,
  'MenuUnfoldOutlined': MenuUnfoldOutlined,
  'MenuFoldOutlined': MenuFoldOutlined,
  'UsergroupDeleteOutlined': UsergroupDeleteOutlined,
  'BarChartOutlined': BarChartOutlined,
  'UnorderedListOutlined': UnorderedListOutlined,
  'EditOutlined': EditOutlined,
  'DashboardOutlined': DashboardOutlined,
  'HomeOutlined': HomeOutlined,
  'FileTextOutlined': FileTextOutlined,
  'PlusOutlined': PlusOutlined,
  'MessageOutlined': MessageOutlined,
  'ProfileOutlined': ProfileOutlined
};

import {
  ref, reactive, watch, h, provide, onMounted, computed, onBeforeUpdate
} from 'vue';
import { useRoute, onBeforeRouteUpdate  } from 'vue-router';
import router from '../router/index.ts'

const route = useRoute();
const collapsed = ref(false);
// import {
//   UserOutlined, MailOutlined, AppstoreOutlined, SettingOutlined, UploadOutlined, MenuUnfoldOutlined, MenuFoldOutlined, UsergroupDeleteOutlined, BarChartOutlined,
//   UnorderedListOutlined,
//   EditOutlined
// } from '@ant-design/icons-vue';
provide('collapsed', collapsed)
import MainPage from '../components/MainPage.vue';

import Header from './Header.vue'
import Breadcrumb from '../components/Breadcrumb.vue'
import { generateMenuFromRoutes, getActiveMenuKey, getOpenMenuKeys } from '../utils/menu'
import { getCurrentUser } from '../utils/auth'
import { debugMenu } from '../utils/menuDebug'
// 获取用户信息
const user = getCurrentUser();
const userRoles = user?.roles || [];
const userPermissions = user?.permissions || [];

// 生成菜单项
const getItem = (label, key, icon, children, type) => ({ label, key, icon, children, type })

// 获取路由配置
const routeConfig = router.getRoutes().find(r => r.name === 'home')?.children || [];

// 生成菜单
const menuItems = generateMenuFromRoutes(routeConfig, userRoles, userPermissions);

console.log('根据当前路由config 和用户角色 生成的 菜单列表： ');
console.dir(menuItems);

// 调试菜单结构
if (process.env.NODE_ENV === 'development') {
  debugMenu.printMenuStructure(menuItems);
}

// 转换为Ant Design菜单格式
const convertToAntMenu = (items) => {
  return items.map(item => {
    const menuItem = {
      key: item.key,
      label: item.title,
      icon: item.icon && iconMap[item.icon] ? () => h(iconMap[item.icon]) : undefined,
      children: item.children ? convertToAntMenu(item.children) : undefined
    };
    
    // 过滤掉没有children的undefined
    if (!menuItem.children) {
      delete menuItem.children;
    }
    
    return menuItem;
  });
};

const items = computed(() => convertToAntMenu(menuItems));
console.log('转换为Ant Design菜单格式后的菜单列表： ');
console.dir(items);
// 当前选中菜单
const selectedKeys = computed(() => {
  const keys = getActiveMenuKey(route.path, menuItems);
  console.log('当前路径:', route.path, '选中菜单:', keys);
  return keys;
});

// 当前展开的菜单
const openKeys = computed(() => {
  const keys = getOpenMenuKeys(route.path, menuItems);
  console.log('当前路径:', route.path, '展开菜单:', keys);
  return keys;
});


const handleClick = e => {
  console.log('菜单点击:', e);
  
  // 查找对应的菜单项
  const findMenuItem = (items, key) => {
    for (const item of items) {
      if (item.key === key) {
        return item;
      }
      if (item.children) {
        const found = findMenuItem(item.children, key);
        if (found) return found;
      }
    }
    return null;
  };
  
  const menuItem = findMenuItem(menuItems, e.key);
  
  if (menuItem && menuItem.path) {
    // 如果有路径，则跳转
    router.push({
      path: menuItem.path
    });
  } else if (e.key === 'main') {
    // 特殊处理：数据总览菜单点击跳转到首页
    router.push('/');
  } else {
    // 如果没有路径，可能是父菜单，不进行跳转
    console.log('父菜单，不进行跳转');
  }
};
function toggleCollapsed() {
  collapsed.value = !collapsed.value;

}
onMounted(() => {
  setStyleBasedOnScreenSize();
  window.addEventListener('resize', setStyleBasedOnScreenSize);

})

function setStyleBasedOnScreenSize() {
  const contentDiv = document.getElementById('content');
  const screenWidth = window.innerWidth;

  if (screenWidth < 768) {
    collapsed.value = true;
  } else if (screenWidth < 1024) {
    collapsed.value = true
  } else {
    collapsed.value = false;
  }
}
</script>
<style>
#components-layout-demo-custom-trigger .trigger:hover {
  color: #1890ff;
}

.logo {
  height: 32px;
  background: rgba(255, 255, 255, 0.3);
  margin: 16px;
}

.site-layout .site-layout-background {
  background: #fff;
}
</style>